package com.spc.car.common.utils.text.gson;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateTypeEmptyToNullAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
    private static final Logger log = LoggerFactory.getLogger(DateTypeEmptyToNullAdapter.class);
    private final String datePattern = "yyyy-MM-dd HH:mm:ss";

    public DateTypeEmptyToNullAdapter() {
    }

    public JsonElement serialize(Date src, Type arg1, JsonSerializationContext arg2) {
        String dateFormatAsString = DateFormatUtils.format(new Date(src.getTime()), "yyyy-MM-dd HH:mm:ss");
        return new JsonPrimitive(dateFormatAsString);
    }

    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!(json instanceof JsonPrimitive)) {
            throw new JsonParseException("The date should be a string value");
        } else {
            try {
                String content = json.getAsString();
                Date date = null;
                if (null != content && !content.trim().isEmpty()) {
                    date = DateUtils.parseDate(content, new String[]{"yyyy-MM-dd HH:mm:ss"});
                }

                return date;
            } catch (NumberFormatException var6) {
                log.info("DateTypeAdapter input date value:{}", json.getAsString());
                return null;
            } catch (ParseException var7) {
                throw new JsonParseException(var7);
            }
        }
    }
}
